package com.nowcoder.community.controller;

import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.SearchResult;
import com.nowcoder.community.service.ElasticsearchService;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Title: SearchController</p>
 * <p>author 12427</p>
 *
 * @version ver1.0
 * @date 2022/8/22 21:27
 */
@Controller
public class SearchController  implements CommunityConstant {

    @Autowired
    private ElasticsearchService elasticsearchService ;

    @Autowired
    private UserService userService ;

    @Autowired
    private LikeService likeService ;


    // search?keyword=xxx
    @RequestMapping(path = "/search" , method = RequestMethod.GET)
    public String search(String keyword , Page page , Model model) throws IOException {

        // 搜索帖子
        SearchResult searchResult = elasticsearchService.searchDiscussPost(keyword, (page.getCurrent() - 1)*10, page.getLimit());

        // 聚合数据
        List<Map<String,Object>> discussPosts = new ArrayList<>() ;
        List<DiscussPost> list = searchResult.getList();
        if(searchResult != null) {
            for(DiscussPost post : list){
                Map<String, Object> map = new HashMap<>();
                map.put("post" , post) ;

                // 帖子作者
                map.put("user" , userService.findUserById(post.getUserId())) ;

                // 点赞数量
                map.put("like" ,  likeService.findEntityLikeCount( ENTITY_TYPE_POST, post.getId())) ;

                discussPosts.add(map) ;
            }
        }
        model.addAttribute("discussPosts" , discussPosts) ;


        model.addAttribute("keyword" , keyword) ;

        page.setPath("/search?keyword=" + keyword );
        page.setRows(searchResult == null ? 0 : (int) searchResult.getTotal());

        return "/site/search" ;
    }

}
